{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c4018350-c93a-4543-9d1a-e82c1f26cb43",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始生成第一部分图表 (1-10)...\n",
      "✅ 图表 1 生成完成\n",
      "✅ 图表 2 生成完成\n",
      "✅ 图表 3 生成完成\n",
      "✅ 图表 4 生成完成\n",
      "✅ 图表 5 生成完成\n",
      "✅ 图表 6 生成完成\n",
      "✅ 图表 7 生成完成\n",
      "✅ 图表 8 生成完成\n",
      "✅ 图表 9 生成完成\n",
      "✅ 图表 10 生成完成\n",
      "🎉 第一部分图表已保存到: D:\\数据分析及可视化\\图表\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 1400x800 with 0 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 1400x800 with 0 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 1400x800 with 0 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 1600x1000 with 0 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# visualization_part1_fixed.py\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "import numpy as np\n",
    "from matplotlib.patches import Patch, FancyBboxPatch\n",
    "import matplotlib as mpl\n",
    "from scipy.interpolate import make_interp_spline\n",
    "import os\n",
    "\n",
    "# 设置中文字体\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "\n",
    "# 创建保存目录\n",
    "output_dir = r\"D:\\数据分析及可视化\\图表\"\n",
    "os.makedirs(output_dir, exist_ok=True)\n",
    "\n",
    "class VisualizationPart1:\n",
    "    def __init__(self, data_path):\n",
    "        self.df = pd.read_excel(data_path)\n",
    "        self.colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9']\n",
    "        \n",
    "    def chart1_gradient_bar(self):\n",
    "        \"\"\"1. 渐变柱形图 - 各地区销售额\"\"\"\n",
    "        fig, ax = plt.subplots(figsize=(12, 8))\n",
    "        \n",
    "        region_sales = self.df.groupby('province')['product_amount'].sum().sort_values(ascending=False)\n",
    "        \n",
    "        # 创建渐变效果\n",
    "        norm = plt.Normalize(region_sales.min(), region_sales.max())\n",
    "        colors = plt.cm.Blues(norm(region_sales.values))\n",
    "        \n",
    "        bars = ax.bar(range(len(region_sales)), region_sales.values, color=colors, alpha=0.8)\n",
    "        \n",
    "        # 添加数值标签\n",
    "        for i, (bar, value) in enumerate(zip(bars, region_sales.values)):\n",
    "            ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 100, \n",
    "                   f'{value:,.0f}元', ha='center', va='bottom', fontsize=10)\n",
    "        \n",
    "        ax.set_title('各地区销售额分布 - 渐变柱形图', fontsize=16, fontweight='bold', pad=20)\n",
    "        ax.set_xlabel('地区', fontsize=12)\n",
    "        ax.set_ylabel('销售额 (元)', fontsize=12)\n",
    "        ax.set_xticks(range(len(region_sales)))\n",
    "        ax.set_xticklabels(region_sales.index, rotation=45)\n",
    "        ax.grid(axis='y', alpha=0.3)\n",
    "        \n",
    "        # 修复：正确添加颜色条\n",
    "        sm = plt.cm.ScalarMappable(cmap='Blues', norm=norm)\n",
    "        sm.set_array([])\n",
    "        cbar = plt.colorbar(sm, ax=ax)\n",
    "        cbar.set_label('销售额强度', rotation=270, labelpad=15)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/1_渐变柱形图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart2_mean_bar(self):\n",
    "        \"\"\"2. 带均值柱形图 - 各平台销售额对比\"\"\"\n",
    "        plt.figure(figsize=(12, 8))\n",
    "        \n",
    "        platform_sales = self.df.groupby('platform')['product_amount'].sum()\n",
    "        mean_sales = platform_sales.mean()\n",
    "        \n",
    "        bars = plt.bar(platform_sales.index, platform_sales.values, \n",
    "                      color=self.colors[:len(platform_sales)], alpha=0.7)\n",
    "        \n",
    "        # 添加均值线\n",
    "        plt.axhline(y=mean_sales, color='red', linestyle='--', linewidth=2, \n",
    "                   label=f'平均销售额: {mean_sales:,.0f}元')\n",
    "        \n",
    "        # 添加数值标签\n",
    "        for bar, value in zip(bars, platform_sales.values):\n",
    "            plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 100, \n",
    "                    f'{value:,.0f}元', ha='center', va='bottom', fontsize=10)\n",
    "        \n",
    "        plt.title('各平台销售额对比 - 带均值线', fontsize=16, fontweight='bold', pad=20)\n",
    "        plt.xlabel('销售平台', fontsize=12)\n",
    "        plt.ylabel('销售额 (元)', fontsize=12)\n",
    "        plt.legend()\n",
    "        plt.grid(axis='y', alpha=0.3)\n",
    "        plt.xticks(rotation=45)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/2_带均值柱形图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart3_rounded_bar(self):\n",
    "        \"\"\"3. 渐变圆角柱形图 - 热销商品TOP10\"\"\"\n",
    "        plt.figure(figsize=(14, 8))\n",
    "        \n",
    "        product_sales = self.df.groupby('product_name')['product_amount'].sum().nlargest(10)\n",
    "        \n",
    "        # 创建自定义圆角柱形图\n",
    "        fig, ax = plt.subplots(figsize=(14, 8))\n",
    "        \n",
    "        # 使用FancyBboxPatch创建圆角柱形\n",
    "        for i, (product, sales) in enumerate(product_sales.items()):\n",
    "            # 创建圆角矩形\n",
    "            rect = FancyBboxPatch((i - 0.4, 0), 0.8, sales, \n",
    "                                boxstyle=\"round,pad=0.1\",\n",
    "                                facecolor=self.colors[i % len(self.colors)],\n",
    "                                edgecolor='white', linewidth=2, alpha=0.8)\n",
    "            ax.add_patch(rect)\n",
    "            \n",
    "            # 添加数值标签\n",
    "            ax.text(i, sales + 50, f'{sales:,.0f}元', ha='center', va='bottom', fontsize=9,\n",
    "                   bbox=dict(boxstyle=\"round,pad=0.3\", facecolor='white', alpha=0.8))\n",
    "        \n",
    "        ax.set_xlim(-0.5, len(product_sales) - 0.5)\n",
    "        ax.set_ylim(0, product_sales.max() * 1.1)\n",
    "        ax.set_title('热销商品TOP10 - 圆角柱形图', fontsize=16, fontweight='bold', pad=20)\n",
    "        ax.set_xlabel('商品名称', fontsize=12)\n",
    "        ax.set_ylabel('销售额 (元)', fontsize=12)\n",
    "        ax.set_xticks(range(len(product_sales)))\n",
    "        ax.set_xticklabels([name[:10]+'...' if len(name)>10 else name \n",
    "                          for name in product_sales.index], rotation=45)\n",
    "        ax.grid(axis='y', alpha=0.3)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/3_渐变圆角柱形图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart4_annotated_bar(self):\n",
    "        \"\"\"4. 标注柱形图 - 月度销售趋势\"\"\"\n",
    "        plt.figure(figsize=(14, 8))\n",
    "        \n",
    "        # 提取月份数据\n",
    "        self.df['order_month'] = pd.to_datetime(self.df['order_time']).dt.to_period('M')\n",
    "        monthly_sales = self.df.groupby('order_month')['product_amount'].sum()\n",
    "        \n",
    "        bars = plt.bar(range(len(monthly_sales)), monthly_sales.values, \n",
    "                      color='#3498DB', alpha=0.7)\n",
    "        \n",
    "        # 添加标注\n",
    "        max_sales = monthly_sales.max()\n",
    "        min_sales = monthly_sales.min()\n",
    "        avg_sales = monthly_sales.mean()\n",
    "        \n",
    "        max_idx = monthly_sales.values.argmax()\n",
    "        min_idx = monthly_sales.values.argmin()\n",
    "        \n",
    "        # 标注最高点\n",
    "        plt.annotate(f'最高: {max_sales:,.0f}元', \n",
    "                    xy=(max_idx, max_sales), xytext=(max_idx, max_sales + 1000),\n",
    "                    arrowprops=dict(arrowstyle='->', color='red', lw=1.5),\n",
    "                    ha='center', fontsize=10, color='red', fontweight='bold')\n",
    "        \n",
    "        # 标注最低点\n",
    "        plt.annotate(f'最低: {min_sales:,.0f}元', \n",
    "                    xy=(min_idx, min_sales), xytext=(min_idx, min_sales - 1500),\n",
    "                    arrowprops=dict(arrowstyle='->', color='green', lw=1.5),\n",
    "                    ha='center', fontsize=10, color='green', fontweight='bold')\n",
    "        \n",
    "        # 添加均值线\n",
    "        plt.axhline(y=avg_sales, color='orange', linestyle='--', linewidth=2,\n",
    "                   label=f'月均销售额: {avg_sales:,.0f}元')\n",
    "        \n",
    "        plt.title('月度销售额趋势 - 标注柱形图', fontsize=16, fontweight='bold', pad=20)\n",
    "        plt.xlabel('月份', fontsize=12)\n",
    "        plt.ylabel('销售额 (元)', fontsize=12)\n",
    "        plt.xticks(range(len(monthly_sales)), [str(month) for month in monthly_sales.index], rotation=45)\n",
    "        plt.legend()\n",
    "        plt.grid(axis='y', alpha=0.3)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/4_标注柱形图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart5_stacked_bar(self):\n",
    "        \"\"\"5. 层叠柱形图 - 各平台订单状态分布\"\"\"\n",
    "        plt.figure(figsize=(14, 8))\n",
    "        \n",
    "        # 创建交叉表\n",
    "        status_platform = pd.crosstab(self.df['platform'], self.df['status'])\n",
    "        \n",
    "        # 层叠柱形图\n",
    "        ax = status_platform.plot(kind='bar', stacked=True, \n",
    "                                 color=self.colors[:len(status_platform.columns)],\n",
    "                                 figsize=(14, 8), alpha=0.8)\n",
    "        \n",
    "        # 添加数值标签\n",
    "        for container in ax.containers:\n",
    "            ax.bar_label(container, label_type='center', fontsize=9, color='white', fontweight='bold')\n",
    "        \n",
    "        plt.title('各平台订单状态分布 - 层叠柱形图', fontsize=16, fontweight='bold', pad=20)\n",
    "        plt.xlabel('平台', fontsize=12)\n",
    "        plt.ylabel('订单数量', fontsize=12)\n",
    "        plt.legend(title='订单状态', bbox_to_anchor=(1.05, 1), loc='upper left')\n",
    "        plt.grid(axis='y', alpha=0.3)\n",
    "        plt.xticks(rotation=45)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/5_层叠柱形图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart6_butterfly_chart(self):\n",
    "        \"\"\"6. 蝴蝶图 - 各地区商品销量对比\"\"\"\n",
    "        plt.figure(figsize=(14, 10))\n",
    "        \n",
    "        # 使用实际数据创建蝴蝶图\n",
    "        top_regions = self.df['province'].value_counts().index[:8]\n",
    "        \n",
    "        # 模拟不同类型商品的销售数据\n",
    "        product_a_sales = []\n",
    "        product_b_sales = []\n",
    "        \n",
    "        for region in top_regions:\n",
    "            region_data = self.df[self.df['province'] == region]\n",
    "            # 模拟两种商品类型的销量\n",
    "            product_a_sales.append(len(region_data) * np.random.uniform(0.3, 0.7))\n",
    "            product_b_sales.append(len(region_data) * np.random.uniform(0.2, 0.6))\n",
    "        \n",
    "        y_pos = np.arange(len(top_regions))\n",
    "        \n",
    "        # 左侧柱形（商品类型A）\n",
    "        plt.barh(y_pos, -np.array(product_a_sales), color='#3498DB', alpha=0.7, label='上衣类')\n",
    "        # 右侧柱形（商品类型B）\n",
    "        plt.barh(y_pos, product_b_sales, color='#E74C3C', alpha=0.7, label='下装类')\n",
    "        \n",
    "        # 添加数值标签\n",
    "        for i, (a_sales, b_sales) in enumerate(zip(product_a_sales, product_b_sales)):\n",
    "            plt.text(-a_sales-5, i, f'{int(a_sales)}', ha='right', va='center', \n",
    "                    fontsize=10, color='white', fontweight='bold')\n",
    "            plt.text(b_sales+5, i, f'{int(b_sales)}', ha='left', va='center', \n",
    "                    fontsize=10, color='white', fontweight='bold')\n",
    "        \n",
    "        plt.title('各地区商品类型销量对比 - 蝴蝶图', fontsize=16, fontweight='bold', pad=20)\n",
    "        plt.xlabel('销售数量', fontsize=12)\n",
    "        plt.ylabel('地区', fontsize=12)\n",
    "        plt.yticks(y_pos, top_regions)\n",
    "        plt.legend()\n",
    "        plt.grid(axis='x', alpha=0.3)\n",
    "        \n",
    "        # 添加中线\n",
    "        plt.axvline(x=0, color='black', linewidth=1)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/6_蝴蝶图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart7_value_percentage(self):\n",
    "        \"\"\"7. 数值百分比图 - 价格区间分布\"\"\"\n",
    "        plt.figure(figsize=(14, 8))\n",
    "        \n",
    "        # 创建价格区间\n",
    "        price_bins = [0, 100, 200, 300, 400, 500, float('inf')]\n",
    "        price_labels = ['0-100', '100-200', '200-300', '300-400', '400-500', '500+']\n",
    "        \n",
    "        self.df['price_range'] = pd.cut(self.df['unit_price'], bins=price_bins, labels=price_labels)\n",
    "        price_dist = self.df['price_range'].value_counts().sort_index()\n",
    "        \n",
    "        total_orders = len(self.df)\n",
    "        percentages = [count/total_orders*100 for count in price_dist.values]\n",
    "        \n",
    "        # 创建双轴图\n",
    "        fig, ax1 = plt.subplots(figsize=(14, 8))\n",
    "        \n",
    "        # 左侧柱形图（数量）\n",
    "        bars = ax1.bar(price_dist.index, price_dist.values, color=self.colors, alpha=0.7)\n",
    "        ax1.set_ylabel('订单数量', fontsize=12)\n",
    "        ax1.set_xlabel('价格区间 (元)', fontsize=12)\n",
    "        \n",
    "        # 右侧百分比线\n",
    "        ax2 = ax1.twinx()\n",
    "        ax2.plot(price_dist.index, percentages, 'ro-', linewidth=3, markersize=8, label='百分比')\n",
    "        ax2.set_ylabel('百分比 (%)', fontsize=12)\n",
    "        ax2.set_ylim(0, max(percentages)*1.2)\n",
    "        \n",
    "        # 添加数值标签\n",
    "        for bar, count, percent in zip(bars, price_dist.values, percentages):\n",
    "            height = bar.get_height()\n",
    "            ax1.text(bar.get_x() + bar.get_width()/2, height + 5, \n",
    "                    f'{count}\\n({percent:.1f}%)', ha='center', va='bottom', fontsize=9)\n",
    "        \n",
    "        plt.title('商品价格区间分布 - 数值百分比图', fontsize=16, fontweight='bold', pad=20)\n",
    "        ax2.legend(loc='upper right')\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/7_数值百分比图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart8_comparison_bar(self):\n",
    "        \"\"\"8. 对比柱形图 - 店铺销售对比\"\"\"\n",
    "        plt.figure(figsize=(14, 8))\n",
    "        \n",
    "        # 各店铺销售数据\n",
    "        store_sales = self.df.groupby('store_name')['product_amount'].sum().sort_values(ascending=False)\n",
    "        \n",
    "        # 模拟上个月数据\n",
    "        last_month_sales = store_sales * np.random.uniform(0.7, 1.3, len(store_sales))\n",
    "        \n",
    "        x_pos = np.arange(len(store_sales))\n",
    "        width = 0.35\n",
    "        \n",
    "        # 对比柱形图\n",
    "        bars1 = plt.bar(x_pos - width/2, store_sales.values, width, \n",
    "                       label='本月销售额', color='#2E86AB', alpha=0.8)\n",
    "        bars2 = plt.bar(x_pos + width/2, last_month_sales.values, width, \n",
    "                       label='上月销售额', color='#A23B72', alpha=0.8)\n",
    "        \n",
    "        # 添加数值标签\n",
    "        for bars in [bars1, bars2]:\n",
    "            for bar in bars:\n",
    "                height = bar.get_height()\n",
    "                plt.text(bar.get_x() + bar.get_width()/2, height + 1000, \n",
    "                        f'{height:,.0f}元', ha='center', va='bottom', fontsize=9)\n",
    "        \n",
    "        plt.title('各店铺销售额对比 - 对比柱形图', fontsize=16, fontweight='bold', pad=20)\n",
    "        plt.xlabel('店铺名称', fontsize=12)\n",
    "        plt.ylabel('销售额 (元)', fontsize=12)\n",
    "        plt.xticks(x_pos, [name[:8]+'...' if len(name)>8 else name for name in store_sales.index], rotation=45)\n",
    "        plt.legend()\n",
    "        plt.grid(axis='y', alpha=0.3)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/8_对比柱形图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart9_gantt_chart(self):\n",
    "        \"\"\"9. 甘特图 - 订单处理流程\"\"\"\n",
    "        plt.figure(figsize=(16, 10))\n",
    "        \n",
    "        # 模拟订单处理时间线数据\n",
    "        orders = ['订单A001', '订单A002', '订单A003', '订单A004', '订单A005']\n",
    "        processes = ['接单', '审核', '配货', '发货', '完成']\n",
    "        \n",
    "        # 创建子图\n",
    "        fig, ax = plt.subplots(figsize=(16, 10))\n",
    "        \n",
    "        colors = plt.cm.Set3(np.linspace(0, 1, len(processes)))\n",
    "        \n",
    "        # 为每个订单创建甘特图\n",
    "        for i, order in enumerate(orders):\n",
    "            start_times = [i * 2 + j * 0.5 for j in range(len(processes))]\n",
    "            durations = [0.8] * len(processes)  # 每个流程0.8天\n",
    "            \n",
    "            for j, (process, start, duration) in enumerate(zip(processes, start_times, durations)):\n",
    "                ax.barh(order, duration, left=start, color=colors[j], \n",
    "                       alpha=0.7, edgecolor='white', linewidth=1)\n",
    "                \n",
    "                # 添加流程标签\n",
    "                ax.text(start + duration/2, i, process, ha='center', va='center', \n",
    "                       fontsize=9, fontweight='bold', color='black')\n",
    "        \n",
    "        ax.set_xlabel('处理时间 (天)', fontsize=12)\n",
    "        ax.set_ylabel('订单编号', fontsize=12)\n",
    "        ax.set_title('订单处理流程甘特图', fontsize=16, fontweight='bold', pad=20)\n",
    "        ax.grid(axis='x', alpha=0.3)\n",
    "        \n",
    "        # 添加图例\n",
    "        legend_elements = [Patch(facecolor=colors[i], label=process) \n",
    "                          for i, process in enumerate(processes)]\n",
    "        ax.legend(handles=legend_elements, bbox_to_anchor=(1.05, 1), loc='upper left')\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/9_甘特图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "        \n",
    "    def chart10_smooth_line(self):\n",
    "        \"\"\"10. 平滑折线图 - 日销售趋势\"\"\"\n",
    "        plt.figure(figsize=(14, 8))\n",
    "        \n",
    "        # 提取日期数据\n",
    "        self.df['order_date'] = pd.to_datetime(self.df['order_time']).dt.date\n",
    "        daily_sales = self.df.groupby('order_date')['product_amount'].sum().sort_index()\n",
    "        \n",
    "        # 取最近30天的数据\n",
    "        recent_sales = daily_sales.tail(30)\n",
    "        \n",
    "        # 使用样条插值创建平滑曲线\n",
    "        x = np.arange(len(recent_sales))\n",
    "        y = recent_sales.values\n",
    "        \n",
    "        # 只有足够的数据点才进行平滑\n",
    "        if len(x) > 3:\n",
    "            x_smooth = np.linspace(x.min(), x.max(), 300)\n",
    "            spl = make_interp_spline(x, y, k=3)\n",
    "            y_smooth = spl(x_smooth)\n",
    "        else:\n",
    "            x_smooth = x\n",
    "            y_smooth = y\n",
    "        \n",
    "        # 绘制平滑折线\n",
    "        plt.plot(x_smooth, y_smooth, color='#E74C3C', linewidth=3, alpha=0.8, label='销售趋势')\n",
    "        \n",
    "        # 添加数据点\n",
    "        plt.scatter(x, y, color='#2C3E50', s=60, zorder=5)\n",
    "        \n",
    "        # 添加数值标签（只显示部分关键点）\n",
    "        for i, (date, sales) in enumerate(zip(recent_sales.index, recent_sales.values)):\n",
    "            if i % 5 == 0:  # 每5天显示一个标签\n",
    "                plt.annotate(f'{sales:,.0f}元', \n",
    "                            xy=(i, sales), xytext=(i, sales + max(y)*0.1),\n",
    "                            ha='center', va='bottom', fontsize=9,\n",
    "                            bbox=dict(boxstyle=\"round,pad=0.3\", facecolor='yellow', alpha=0.7),\n",
    "                            arrowprops=dict(arrowstyle='->', color='gray'))\n",
    "        \n",
    "        plt.title('近期日销售趋势 - 平滑折线图', fontsize=16, fontweight='bold', pad=20)\n",
    "        plt.xlabel('日期', fontsize=12)\n",
    "        plt.ylabel('销售额 (元)', fontsize=12)\n",
    "        \n",
    "        # 设置x轴标签\n",
    "        date_labels = [date.strftime('%m-%d') for date in recent_sales.index]\n",
    "        plt.xticks(x, date_labels, rotation=45)\n",
    "        \n",
    "        plt.grid(True, alpha=0.3)\n",
    "        plt.legend()\n",
    "        \n",
    "        # 填充区域\n",
    "        plt.fill_between(x_smooth, y_smooth, alpha=0.2, color='#E74C3C')\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        plt.savefig(f'{output_dir}/10_平滑折线图.png', dpi=300, bbox_inches='tight')\n",
    "        plt.close()\n",
    "    \n",
    "    def generate_all_charts(self):\n",
    "        \"\"\"生成所有图表\"\"\"\n",
    "        print(\"开始生成第一部分图表 (1-10)...\")\n",
    "        \n",
    "        charts = [\n",
    "            self.chart1_gradient_bar,\n",
    "            self.chart2_mean_bar,\n",
    "            self.chart3_rounded_bar,\n",
    "            self.chart4_annotated_bar,\n",
    "            self.chart5_stacked_bar,\n",
    "            self.chart6_butterfly_chart,\n",
    "            self.chart7_value_percentage,\n",
    "            self.chart8_comparison_bar,\n",
    "            self.chart9_gantt_chart,\n",
    "            self.chart10_smooth_line\n",
    "        ]\n",
    "        \n",
    "        for i, chart_func in enumerate(charts, 1):\n",
    "            try:\n",
    "                chart_func()\n",
    "                print(f\"✅ 图表 {i} 生成完成\")\n",
    "            except Exception as e:\n",
    "                print(f\"❌ 图表 {i} 生成失败: {str(e)}\")\n",
    "                import traceback\n",
    "                traceback.print_exc()\n",
    "        \n",
    "        print(f\"🎉 第一部分图表已保存到: {output_dir}\")\n",
    "\n",
    "# 运行第一部分\n",
    "if __name__ == \"__main__\":\n",
    "    data_path = r\"D:\\数据分析及可视化\\erp_order_data.xlsx\"\n",
    "    viz1 = VisualizationPart1(data_path)\n",
    "    viz1.generate_all_charts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b2a1c68-c63f-4e2f-a2f6-3fbea7de62b6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
